package com.xiaoming;

import com.xiaoming.annotation.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DispatchServlet extends HttpServlet {
    // 配置文件
    private Properties properties = new Properties();
    // ioc
    private Map<String, Object> ioc = new HashMap<>();
    // 扫描到的类
    private List<String> classNames = new ArrayList<>();
    // url映射
    private List<Handler> handlers = new ArrayList<>();
    private int length;


    @Override
    public void init(ServletConfig config) throws ServletException {
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        // 加载配置
        doLoadConfig(contextConfigLocation);
        // 扫描类
        doScan(properties.getProperty("scan.package"));
        // 初始化Bean
        initBean();
        // 依赖注入
        doAutoWired();
        // 映射
        initRequestMapping();
        initSecurity();
    }

    private void initSecurity() {
        for (Handler handler : handlers) {
            Method method = handler.getMethod();
            Object controller = handler.getController();
            Map<String,Integer> securitiesMap = new HashMap<>();
            Boolean controllerHasSecurity = false;
            if (controller.getClass().isAnnotationPresent(Security.class)) {
                Security annotation = controller.getClass().getAnnotation(Security.class);
                controllerHasSecurity = true;
                for (String name :annotation.names()) {
                    securitiesMap.put(name.trim(),1);
                }
            }
            if (method.isAnnotationPresent(Security.class)) {
                Security annotation = method.getAnnotation(Security.class);
                for (String name :annotation.names()) {
                    String trimName = name.trim();
                    if(securitiesMap.containsKey(trimName)){
                        securitiesMap.put(trimName,2);
                    }else {
                        securitiesMap.put(trimName,1);
                    }
                }
            }
            List<String> securities = new ArrayList<>();
            for (Map.Entry <String,Integer>entry: securitiesMap.entrySet()) {
                if(controllerHasSecurity && entry.getValue() ==2){
                    securities.add(entry.getKey());
                }else if(!controllerHasSecurity){
                    securities.add(entry.getKey());
                }

            }
            handler.setSecurities(securities);
        }
    }

    private void initRequestMapping() {
        for (Map.Entry entry : ioc.entrySet()) {
            if (!entry.getValue().getClass().isAnnotationPresent(Controller.class)) {
                continue;
            }
            String url = "";
            if (entry.getValue().getClass().isAnnotationPresent(RequestMapping.class)) {
                RequestMapping mapping = entry.getValue().getClass().getAnnotation(RequestMapping.class);
                url = mapping.value();
            }
            Method[] methods = entry.getValue().getClass().getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(RequestMapping.class)) {
                    continue;
                }

                url += method.getAnnotation(RequestMapping.class).value();
                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));
                Parameter[] parameters = method.getParameters();

                LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
                String[] params = u.getParameterNames(method);

                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    if (HttpServletRequest.class == parameter.getType() ||
                            HttpServletResponse.class == parameter.getType()) {
                        handler.getParamIndexMap().put(parameter.getType().getSimpleName(), i);
                    } else {
                        handler.getParamIndexMap().put(params[i], i);
                    }
                }
                handlers.add(handler);

            }

        }
    }

    private void doAutoWired() {
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    Autowired annotation = field.getAnnotation(Autowired.class);
                    String beanName = annotation.value().trim();
                    if ("".equals(beanName)) {
                        beanName = field.getType().getName();
                    }
                    field.setAccessible(true);
                    try {
                        field.set(entry.getValue(), ioc.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void initBean() {
        try {

            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i);
                Class<?> aClass = Class.forName(className);
                if (aClass.isAnnotationPresent(Controller.class)) {
                    Object o = aClass.getDeclaredConstructor().newInstance();
                    ioc.put(lowerFirst(aClass.getSimpleName()), o);
                } else if (aClass.isAnnotationPresent(Service.class)) {
                    Service service = aClass.getAnnotation(Service.class);
                    Object o = aClass.getDeclaredConstructor().newInstance();
                    String beanName = service.value();
                    if (!"".equals(beanName.trim())) {
                        ioc.put(beanName, o);
                    } else {
                        ioc.put(lowerFirst(aClass.getSimpleName()), o);
                    }
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> superInterface : interfaces) {
                        ioc.put(superInterface.getName(), o);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String lowerFirst(String string) {
        char[] c = string.toCharArray();
        if ('A' <= c[0] && 'Z' >= c[0]) {
            c[0] += 32;
        }
        return String.valueOf(c);
    }

    private void doScan(String packageName) {
        try {
            String packagePath = Thread.currentThread().getContextClassLoader()
                    .getResource("").getPath()
                    + packageName.replaceAll("\\.", "/");
            File pack = new File(packagePath);
            File[] files = pack.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    doScan(packageName + "." + file.getName());
                } else if (file.getName().endsWith(".class")) {
                    String fileName = file.getName();
                    classNames.add(packageName + "." + fileName.substring(0, fileName.lastIndexOf(".class")));
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void doLoadConfig(String contextConfigLocation) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }


        Class<?>[] parameterTypes =
                handler.getMethod().getParameterTypes();
        Object[] paraValues = new Object[parameterTypes.length];
        Map<String, String[]> parameterMap = req.getParameterMap();
        if (handler.getSecurities().size() != 0) {
            if (!parameterMap.containsKey("userName") ||
                    !handler.getSecurities().contains(parameterMap.get("userName")[0])) {
                resp.getWriter().write("403 No Permission");
                return;
            }
        }
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            String value = StringUtils.join(param.getValue(), ",");

            if (!handler.getParamIndexMap().containsKey(param.getKey())) {
                continue;
            }
            Integer index = handler.getParamIndexMap().get(param.getKey());
            paraValues[index] = value;
            int requestIndex = handler.getParamIndexMap().get(HttpServletRequest.class.getSimpleName());
            paraValues[requestIndex] = req;
            int responseIndex =
                    handler.getParamIndexMap().get(HttpServletResponse.class.getSimpleName
                            ());
            paraValues[responseIndex] = resp;
        }
        try {
            handler.getMethod().invoke(handler.getController(), paraValues);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Handler getHandler(HttpServletRequest req) {
        String url = req.getRequestURI();
        for (Handler handler : handlers) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }
}
